package com.server.model.all.util;

import com.server.model.all.enums.BaseEnum;
import com.server.model.all.enums.EnumParam;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EnumParamValidator implements ConstraintValidator<EnumParam, Integer> {

    private EnumParam constraintAnnotation;

    @Override
    public void initialize(EnumParam constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.constraintAnnotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Integer o, ConstraintValidatorContext constraintValidatorContext) {
        if(!constraintAnnotation.mClass().isEnum()){
            return false;
        }
        Class<?> clazz = constraintAnnotation.mClass();
        //获取所有枚举实例
        BaseEnum[] enumConstants = (BaseEnum[]) clazz.getEnumConstants();
        for (BaseEnum enum1 : enumConstants) {
            if(enum1.getCode().equals(o)){
                return true;
            }
        }
        return false;
    }
}
